﻿using ConfExpert.Forms.Base;
using ConfExpert.Properties;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Satinalma
{
    public partial class ArticleOrders : XForm
    {
        public ArticleOrders()
        {
            InitializeComponent();
        }

        BindingSource bs;
        private void ArticleOrders_Load(object sender, EventArgs e)
        {
            GridManager gm = GridManager.GetManager(gv);
            gm.GridMenu.AddMenu("Bu satırlar için PO oluştur", Olustur, Resources.accept_16);

            bs = gv.Init("COGetArticleOrder3", 75, WhoAmI);
            gv.AddAutoIncrementalPK("ArticleOrderId");
            bs.Filter = "Connected = 'Y' OR ArticleOrderId<0";
            gv.EnableNewRow();            

            gv.MakeColumnInvisible("KCustomerId");
            gv.SetCaptions("ArticleOrderId:#");
            gv.FormatAsDate("RequiredETA", "InsertedOn", "ShirtETD", "OrderDate");
            gv.FormatAsNumber(1, "QtyTalep", "QtyOrdered", "QtyShipped", "QtyArrived", "QtyMissing");
            gv.FormatAsNumber(3, "Price", "BasicShirtPrice", "EurFiyat");
            gv.AddSummary("QtyTalep", "QtyOrdered", "QtyShipped", "QtyArrived", "QtyMissing");
            //gv.OptionsView.NewItemRowPosition = NewItemRowPosition.None;

            DataTable dtOrderRef = Session.DataManager.ExecuteDataTableByQuery("select * from COOrderRef");
            DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit riOrderRef = GetCustomGLE(dtOrderRef, "OrderRef", "OrderRefId");
            riOrderRef.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            gv.Columns["OrderRefId"].ColumnEdit = riOrderRef;

            //gv.Columns["KCustomerId"].ColumnEdit = RI(Rp.V_Customer);
            gv.Columns["Status"].ColumnEdit = RI(Rp.PODurum);

            //AppSession.Lookups.Brand.DefaultView.RowFilter =   "CustomerId=" + Session.CurrentUser.CustomerId;
            gv.MakeReadOnly("ProductId", "KCustomerId", "KVendorId", "QtyTalep", "RequiredETA", "OrderRefId", "PreferredVendorId", "ShirtETD", "Notes", "Notes2", "Quality", "AyrimlarId", "NewArticle", "Price");
            gv.ShowingEditor += gv_ShowingEditor;

            gv.RowCellStyle += gv_RowCellStyle;
            gv.BestFitColumns();

            chkGoster.CheckedChanged += chkGoster_CheckedChanged;
        }

        void gv_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (gv.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
                if (gv.FocusedColumn.FieldName == "AyrimlarId")
                    e.Cancel = gv.GetFocusedDataRow()["PONr"].ToStr() != string.Empty;

            e.Cancel = false;
        }

        void chkGoster_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            bs.Filter = chkGoster.Checked ? string.Empty : "Connected = 'Y'";
            gv.BestFitColumns();
        }

        void Olustur(object sender, EventArgs e)
        {
            int rh = gv.FocusedRowHandle;

            if (gv.SelectedRowsCount < 1)
                gv.SelectRow(gv.FocusedRowHandle);

            string ArticleOrderIds = gv.GetSelectedValues("ArticleOrderId");
            foreach(string i in ArticleOrderIds.Split(",".ToCharArray()))
                if (i.ToInt() < 0)
                {
                    XtraMessageBox.Show("'PO oluştur' demeden önce kaydetmelisiniz.");
                    return;
                }

            gv.EndEditing();
            gv.Update("ArticleOrderId,ProductId,KVendorId,PreferredVendorId,KCustomerId,QtyTalep,ShirtETD,NewArticle,Price", "COArticleOrder");

            List<string> lst = new List<string>();

            DataTable t = ExecuteDataTable("CheckPOForWB", ArticleOrderIds);

            if (t.Select("ProductId is null AND (NewArticle is null OR NewArticle='')").Length > 0)
                lst.Add("ProductId/NewArticle çiftinden en az biri");

            if (t.Select("QtyTalep is null").Length > 0)
                lst.Add("QtyTalep");

            if (t.Select("ShirtETD is null").Length > 0)
                lst.Add("ShirtETD");

            if (t.Select("OrderRefId is null").Length > 0)
                lst.Add("OrderRefId");

            if (lst.Count > 0)
            {
                XtraMessageBox.Show("Seçtiğiniz satırlarda şu alanların tamamı dolu olmak zorunda!" + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, lst.ToArray()));
                return;
            }

            ExecuteNonQuery("InsPOForWB", ArticleOrderIds, WhoAmI);
            gv.RefreshDataSource(true, "COGetArticleOrder3", 75, WhoAmI);

            gv.FocusedRowHandle = rh;
            gv.MakeRowVisible(gv.FocusedRowHandle);
        }

        void gv_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                int QtyArrived = gv.GetRowCellValue(e.RowHandle, "QtyArrived").ToInt();
                switch (e.Column.FieldName)
                {
                    case "QtyTalep":
                    case "QtyOrdered":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, System.Drawing.FontStyle.Bold);
                        //if (QtyArrived>0)
                        //    e.Appearance.ForeColor = Color.Purple;
                        return;
                }
            }
        }

        private void btnSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            int rh = gv.FocusedRowHandle;

            gv.EndEditing();
            gv.Update("ArticleOrderId,ProductId,KVendorId,PreferredVendorId,KCustomerId,QtyTalep,ShirtETD,NewArticle,Price", "COArticleOrder");
            gv.RefreshDataSource(true, "COGetArticleOrder3", 75, WhoAmI);

            gv.FocusedRowHandle = rh;
            gv.MakeRowVisible(gv.FocusedRowHandle);
        }
    }
}
